<template>
  <div class="corpInfo">
    <form>
      <div class="form-item">
        <label class="form-item-left">公司名称</label>
        <div class="form-item-right">
          <input type="text" disabled v-model="companyName">
        </div>
      </div>
      <div class="form-item">
        <label class="form-item-left">法人代表</label>
        <div class="form-item-right">
          <input type="text" disabled v-model="legalPerson">
        </div>
      </div>
      <div class="form-item">
        <label class="form-item-left">公司规模</label>
        <div class="form-item-right">
          <Select
            :disabled="true"
            width="195px"
            v-model="scale"
            placeholder="公司规模">
            <!-- 这里也可以用对象数组 [{},{},{}] 循环，key值不重复就行，value是你要得到的值，双大括号中是你要显示的值 -->
            <Option
              v-for="item of [{key: '0', value: '(1-10)'},
              {key: '1', value: '(11-50)'},
              {key: '2', value: '(51-100)'},
              {key: '3', value: '(101-500)'},
              {key: '4', value: '(501-1000)'},
              {key: '5', value: '(1001-5000) '},
              {key: '6', value: '(5001-10000)'},
              {key: '7', value: '(>10000)'}]"
              :key="item.key"
              :value="item.key">
                {{ item.value }}
            </Option>
          </Select>
        </div>
      </div>
      <div class="form-item">
        <label class="form-item-left">融资情况</label>
        <div class="form-item-right">
          <Select
            :disabled="true"
            width="195px"
            v-model="finacial"
            placeholder="融资情况">
            <Option
              v-for="item of [{key: '0', value: '天使轮'},
              {key: '1', value: 'A轮'},
              {key: '2', value: 'B轮'},
              {key: '3', value: 'C轮'},
              {key: '4', value: '不需要融资'}]"
              :key="item.key"
              :value="item.key">
                {{ item.value }}
            </Option>
          </Select>
        </div>
      </div>
      <div class="form-item">
        <label class="form-item-left">创建时间</label>
        <div class="form-item-right">
          <date-picker
            :single-input="true"
            v-model="date"
            :disabled="true"
            width="195px"></date-picker>
        </div>
      </div>
      <div class="form-item">
        <label class="form-item-left">注册资本</label>
        <div class="form-item-right">
          <input type="text" v-model="capital" disabled>
        </div>
      </div>
      <div class="form-item">
        <label class="form-item-left" >官网地址</label>
        <div class="form-item-right">
          <input type="text" v-model="url">
        </div>
      </div>
      <div class="form-item">
        <label class="form-item-left" >公司地址</label>
        <div class="form-item-right">
          <input type="text" v-model="address">
        </div>
      </div>
      <div class="form-item">
        <label class="form-item-left">公司图标</label>
        <div class="form-item-right">
          <input id="logo" ref="logo" type="file" v-show="false" @change="updateLogo">
          <label for="logo" style="cursor:pointer">
            <div class="banner"></div>
            <img ref="logoImg" width="195px" :src="logoPic">
          </label>
        </div>
      </div>
    </form>
    <form style="padding-bottom: 370px">
      <div class="form-item">
        <label class="form-item-left">公司图片</label>
        <div class="form-item-right">
          <input id="corpImg" type="file" v-show="false" ref="newpic" @change="updateNewPic">
          <label for="corpImg">
            <div class="btn primary">上传</div>
          </label>
          <div class="corpImg-container">
            <div class="corpImgs" v-for="(img, index) of corpImgs" :key="img.id">
              <span style="flex:1">
                <img :src="nginx + img.name" width="200">
              </span>
              <span class="deleteIcon" @click="deleteImg(index)"></span>
            </div>
          </div>
        </div>
      </div>
      <div class="form-item">
        <label class="form-item-left">公司描述</label>
        <div class="form-item-right info-editor">
          <quill-editor
            class="editor"
            :options="editorConfig1"
            v-model="description"
          ></quill-editor>
          <!-- <textarea cols="30" rows="10" v-model="description"></textarea> -->
        </div>
      </div>
    </form>
    <div
      class="btn primary"
      @click="reset"
      style="margin-right:10px;position:absolute;right:0">重置</div>
    <div
      class="btn primary"
      style="position:absolute;right:100px"
      @click="update">修改</div>
  </div>
</template>
<script>
import { corpMixin } from '@/mixins/NavigationGuards';
import { quillEditor } from 'vue-quill-editor';
import Select from '@/components/select/Select';
import Option from '@/components/select/Option';
import DatePicker from '@/components/Date/index';
import api from '@/api/corpInfo';
import nginx from '@/assets/nginxconfig';

async function getCompanyInfo() {
  const response = await api.getCompanyInfoApi(sessionStorage.getItem('companyId'));
  return response.data.data;
}
export default {
  mixins: [corpMixin],
  name: 'CorpInfo',
  data() {
    return {
      companyName: '',
      legalPerson: '',
      capital: '',
      url: '',
      address: '',
      description: '',
      scale: '',
      finacial: '',
      date: null,
      // 公司图片，最多上传3张
      corpImgs: [],
      companyId: '',
      logoPic: '',
      ico: '',
      nginx: nginx.nginxaddress,
      editorConfig1: {
        placeholder: '例如：两年UI设计经验，熟悉IOS和Android的界面设计规范，对产品本色有独特见解，有一定的手冲经验',
        modules: {
          toolbar: [
            [{ list: 'ordered' }, { list: 'bullet' }],
          ],
        },
      },
    };
  },
  beforeRouteEnter(from, to, next) {
    if (sessionStorage.getItem('userToken') === null || sessionStorage.getItem('loginType') !== '2') {
      next({ path: '/login' });
    }
    getCompanyInfo()
      .then((res) => {
        next((vm) => {
          vm.$emit('route-switch', window.location.href.split('/').pop());
          vm.setCompanyInfo(res);
          // eslint-disable-next-line no-param-reassign
          vm.companyId = vm.$store.getters['user/getUserInfo'].companyId;
        });
      });
  },
  components: {
    Select,
    Option,
    DatePicker,
    quillEditor,
  },
  methods: {
    setCompanyInfo(data) {
      this.companyName = data.name;
      this.legalPerson = data.legalPerson;
      this.description = data.description;
      this.capital = data.capital;
      this.url = data.url;
      this.address = data.address;
      this.date = new Date(data.establish);
      this.scale = data.scale;
      this.finacial = data.financing;
      this.logoPic = nginx.nginxaddress + data.ico;
      this.ico = data.ico;
      let pics = [];
      if (data.images) {
        pics = data.images.split(',');
      }
      this.corpImgs = [];
      for (let i = 0; i < pics.length; i += 1) {
        this.corpImgs.push({
          name: pics[i],
          value: nginx.nginxaddress + pics[i],
        });
      }
    },
    updateLogo() {
      if (this.$refs.logo.files[0] !== undefined) {
        this.$confirm('确定要更换公司图标吗？', (res) => {
          if (res === true) {
            const params = new FormData();
            params.append('file', this.$refs.logo.files[0]);
            const that = this;
            api.uploadPic(params).then((response) => {
              // console.log(response.data);
              that.$data.logoPic = nginx.nginxaddress + response.data.data;
              that.$data.ico = response.data.data;
              this.$alert('更改成功');
            });
          } else {
            this.$refs.logo.value = null;
          }
        });
      }
    },
    updateNewPic() {
      if (this.corpImgs.length === 3) {
        this.$alert('最多只能上传3张图片');
        return;
      }
      if (this.$refs.newpic.files[0] !== undefined) {
        this.$confirm('确定要添加图片吗？', (res) => {
          if (res === true) {
            const params = new FormData();
            params.append('file', this.$refs.newpic.files[0]);
            const that = this;
            api.uploadPic(params).then((response) => {
              if (!response.data.data) {
                this.$alert('大小超出限制，限制为1MB');
              } else {
                that.corpImgs.push(
                  {
                    name: response.data.data,
                    value: nginx.nginxaddress + response.data.data,
                  },
                );
                this.$alert('添加成功');
              }
            });
          } else {
            this.$refs.newpic.value = null;
          }
        });
      }
    },
    update() {
      const that = this;
      this.$confirm('确定修改公司信息吗？', (res) => {
        if (res === true) {
          const params = new URLSearchParams();
          params.append('capital', that.$data.capital);
          params.append('url', that.$data.url);
          params.append('description', that.$data.description);
          params.append('address', that.$data.address);
          params.append('ico', that.$data.ico);
          let img = '';
          for (let i = 0; i < that.$data.corpImgs.length; i += 1) {
            if (i === 0) {
              img += that.$data.corpImgs[i].name;
            } else {
              img += `,${that.$data.corpImgs[i].name}`;
            }
          }
          params.append('images', img);
          api.update(that.companyId, params).then(async (response) => {
            // console.log(response.data);
            if (response.data.code === 200) {
              this.$alert('修改成功');
              const info = await getCompanyInfo();
              this.setCompanyInfo(info);
            } else {
              this.$alert('修改失败');
            }
          });
        }
      });
    },
    deleteImg(index) {
      this.$confirm('确定要删除图片吗？', (res) => {
        if (res === true) {
          // TODO 删除图片后台逻辑
          this.corpImgs.splice(index, 1);
          this.$alert('删除成功');
        }
      });
    },
    async reset() {
      const info = await getCompanyInfo();
      this.setCompanyInfo(info);
    },
  },
};
</script>
<style lang="less">
@import url(../../../../static/style/site.comm.less);
@import url(../../../../static/style/site.vars.less);

.corpInfo {
  font-size: 0;
  display: flex;
  justify-content: left;
  background: #fff;
  padding: 10px;
  box-shadow: 0 3px 6px rgba(6,0,1,.05);
  position: relative;
  & > form {
    display: inline-block;
    text-align: left;
    box-sizing: border-box;
    width: 30%;
    padding-left: 0;
    padding-top: 0;
    margin: 0;
    position: relative;
    .form-item {
      justify-content: left;
    }
    .form-item-left {
      width: 80px;
      text-align: left;
    }
    .form-item-right {
      width: 200px;
      position: relative;
      text-align: left;
      &.info-editor {
        position: absolute;
        width: 720px;
        height: 300px;
        left: 104px;
        .ql-editor {
          height: 345px;
        }
      }
    }
    .corpImg-container {
      margin-top: 20px;
      display: flex;
      .corpImgs {
        font-size: 10px;
        width: 250px;
        background: rgb(206, 229, 255);
        display: flex;
        align-items: flex-start;
        box-sizing: border-box;
        // padding: 0 10px 0 10px;
        padding: 10px;
        padding-right: 5px;
        margin-right: 5px;
        margin-top: 5px;
        & > span:nth-child(2) {
          cursor: pointer;
          box-sizing: border-box;
          width: 21px;
          height: 21px;
          text-align: center;
          border-radius: 15px;
          padding-top: 1.5px;
          padding-right: 1px;
          color: #fff;
          background-image: url(../../../assets/img/u532.png);
          background-position: center center;
          background-repeat: no-repeat;
          &:hover {
            background: url(../../../assets/img/u532_mouseOver.png) no-repeat center center;
          }
        }
      }
    }
    textarea {
      padding: 5px;
    }
  }
}
</style>
